package cemp.util;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;


public class StockHttpUtil {

    /**
     * 使用 restTemplate 的exchange方法可以解决 对象中的泛型的序列化和反序列化问题
     * @param restTemplate
     * @param url
     * @param method
     * @param type
     * @return
     */
    public static ResponseEntity doGet(RestTemplate restTemplate,String url, HttpMethod method, ParameterizedTypeReference type){
        return restTemplate.exchange(url, HttpMethod.GET,null,type);
    }

    public static String doHttpByBasicAuth(RestTemplate restTemplate, String url, HttpMethod method, Map<String,String> header, String username, String password){
        // 创建Headers
        HttpHeaders headers = new HttpHeaders();
        headers.setBasicAuth(username, password);
        //装载头信息
        if (header != null){
            header.keySet().forEach(new Consumer<String>() {
                @Override
                public void accept(String key) {
                    headers.set(key,header.get(key));
                }
            });
        }
        // 创建HttpEntity
        HttpEntity<String> entity = new HttpEntity<>(headers);

        // 使用exchange方法
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                method,
                entity,
                String.class
        );
        return response.getBody();
    }
}
